/** ***************************************************************************
 * CoffeeFile.cpp
 * 2012 CoffeeParty Ltd.
 * Date Created: 2012-07-21                                  format YYYY-MM-DD
 * Revision Id: $Id$
 ******************************************************************************
 */

#include "CoffeeCommons.hpp"
#include "CoffeeString.hpp"
#include "CoffeeTypes.hpp"
#include "CoffeeIO.hpp"

CoffeeFile::CoffeeFile(c_const_bytep filename, c_const_bytep mode)
: cfilename(filename)
{
    if (!open(filename, mode))
        return;
}

CoffeeFile::~CoffeeFile()
{
    if (isOpen())
        close();
}

c_string CoffeeFile::filename()
{
    return cfilename;
}

c_size_t CoffeeFile::size() const
{
    return filelength;
}

c_size_t CoffeeFile::read(c_voidp data, c_size_t length)
{
    c_size_t wlength;
    if (!isOpen())
        return 0;

    return (wlength = fread(data, 1, length, file));
}

c_size_t CoffeeFile::write(c_voidp data, c_size_t length)
{
    c_size_t wlength;
    if (!isOpen())
        return 0;

    return (wlength = fwrite(data, 1, length, file));
}

c_byte CoffeeFile::read_byte()
{
    if (!isOpen())
        return '\0';

    return fgetc(file);
}

c_byte CoffeeFile::write_byte(c_byte data)
{
    return fputc(data, file);
}

c_size_t CoffeeFile::pos() const
{
    return ftell(file);
}

c_bool CoffeeFile::seek(c_size_t offset, c_bool relative)
{
    if (!isOpen())
        return false;

    return fseek(file, offset, relative ? SEEK_CUR : SEEK_SET) == 0;
}

c_bool CoffeeFile::isOpen()
{
    return (file != 0);
}

c_bool CoffeeFile::open(c_const_bytep filename, c_const_bytep mode)
{
    file = fopen(filename, mode);
    if (!file)
        return false;

    fseek(file, 0, SEEK_END);
    filelength = ftell(file);
    fseek(file, 0, SEEK_SET);

    return true;
}

c_void CoffeeFile::close()
{
    fclose(file);
}

